(*
 *    _  _   ____                         _  
 *  _| || |_/ ___|  ___ _ __  _ __   ___ | | 
 * |_  ..  _\___ \ / _ \ '_ \| '_ \ / _ \| | 
 * |_      _|___) |  __/ |_) | |_) | (_) |_| 
 *   |_||_| |____/ \___| .__/| .__/ \___/(_) 
 *                     |_|   |_|             
 *
 * Personal Social Web.
 *
 * Copyright (C) The #Seppo contributors. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *)

let () =
  let module Cg = Seppo_lib.Cgi in
  let module E = Seppo_lib.E in
  let module Http = Seppo_lib.Http in
  let module L = Seppo_lib.Logr in
  Mirage_crypto_rng_unix.use_default ();
  let uuid = () |> (() |> Random.State.make_self_init |> Uuidm.v4_gen) in
  let resp_err ec ?(hdrs = [Http.H.ct_plain]) status msg =
    (try L.err (fun m -> m "%a %s %s" Uuidm.pp uuid  ec msg);
     with _ -> ());
    Cg.Response.flush uuid stdout (status, hdrs, fun oc ->
        let s = status |> Cohttp.Code.string_of_status in
        Printf.eprintf "FATAL: %s\r\nsee %s\r\n%s\r\n" s ec msg;
        Printf.fprintf oc "Status: %s\r\n\r\n%s\r\n%s" s ec msg ) in
  (try match Cg.Request.(from_env () |> consolidate |> proxy) with
     | Error _ -> Sys.argv
                  |> Array.to_list
                  |> Shell.exec
     | Ok req -> 
       let uuid = Uuidm.v4_gen (Random.State.make_self_init ()) () in
       req
       |> Cgi.handle uuid stdin
       |> Cg.Response.flush uuid stdout
   with
   | Unix.Unix_error(ENOENT, "chdir", dir) -> resp_err E.e1037 `Internal_server_error ("cd: The directory '" ^ dir ^ "' does not exist")
   | Sys_error msg -> resp_err E.e1034 `Internal_server_error msg
   | e -> resp_err E.e1005 `Internal_server_error (Printexc.to_string e) )
  |> exit
